package com.gjy.disruptor.db;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-08-07 10:52:28
 */
public class DbDisruptor {

    public static void main(String[] args) {
        int ringBufferSize = 1024 * 1024;
        Disruptor<DbEntity> disruptor = new Disruptor<>(new DBEntityEventFactory(), ringBufferSize, Executors.defaultThreadFactory(),
                ProducerType.SINGLE, new YieldingWaitStrategy());

        DbConsumer r1 = new DbConsumer("jdbc:mysql://localhost:3306/liteflow?rewriteBatchedStatements=true&cachePrepStmts=true&prepStmtCacheSize=250&prepStmtCacheSqlLimit=2048", "root", "Oracle@12");
        disruptor.handleEventsWith(r1);
        disruptor.start();

        ExecutorService pool = Executors.newSingleThreadExecutor();
        pool.submit(() -> {
            RingBuffer<DbEntity> ringBuffer = disruptor.getRingBuffer();
            String sqlTemplate = "insert into disruptor_t1 (id, name) values (%s,'%s')";
            for (int i = 0; i < 1000000; i++) {
                ringBuffer.publishEvent(new DbEntityEventTranslator(String.format(sqlTemplate, i, "name: " + i)));
            }
        });
    }
}
